package com.xckj.cycling.fragment

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.inuker.bluetooth.library.Constants.*
import com.junca.android.base.CViewBinding
import com.xckj.cycling.framework.lazyGlobalViewModel
import com.junca.android.service.Request
import com.xckj.cycling.BuildConfig
import com.xckj.cycling.R
import com.xckj.cycling.activity.AddDeviceActivity
import com.xckj.cycling.activity.BrowserActivity
import com.xckj.cycling.activity.MainActivity
import com.xckj.cycling.bean.Equip
import com.xckj.cycling.bean.TodayArr
import com.xckj.cycling.bean.TryRide
import com.xckj.cycling.bean.UserInfoResponseBean
import com.xckj.cycling.bean.common.EventBusBean
import com.xckj.cycling.bean.common.EventTag
import com.xckj.cycling.databinding.FragmentMineBinding
import com.xckj.cycling.dialog.AddCommentDialog
import com.xckj.cycling.dialog.TryRideLicenceShowDialog
import com.xckj.cycling.dialog.UpdateHasCarDialog
import com.xckj.cycling.framework.BaseFragmentKt
import com.xckj.cycling.global.Constant
import com.xckj.cycling.utils.*
import com.xckj.cycling.viewmodel.BleViewModel
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import java.math.RoundingMode
import java.util.*

/**
 * @Author: ChenYao
 * @Describe: 我的
 * @Date: 2023/3/13 22:03
 */
class MineFragment : BaseFragmentKt(), View.OnClickListener {

    @CViewBinding
    lateinit var viewBinding: FragmentMineBinding
    private val bleViewModel: BleViewModel by lazyGlobalViewModel()
    private var model: UserInfoResponseBean? = null
    private var ble = false
    private var lastUpdate = 0L
    private var hasCar = false
    override fun initView(root: View, savedInstanceState: Bundle?) {
        super.initView(root, savedInstanceState)
        checkHasCar()
//        startActivity(Intent(requireActivity(), HealthDelegateActivity::class.java))
        initData()
        setListener()
        loginViewModel.userCenterHeartBeat()
        loginViewModel.unreadHeartBeat()
        loginViewModel.userCenterLiveData.observe(this) {
            model = it
            it ?: return@observe
            if (ble) {
                viewBinding.tvTopBikeName.text = model?.equipment?.name
            }
            Glide.with(requireActivity()).load(it.userinfo?.level_icon)
                .placeholder(R.mipmap.icon_medal).into(viewBinding.medal)
            hasCar = it.userinfo?.bikestatus == 1
            setHasCarOrNoCar(hasCar, it.equipment)
//            ToastUtils.debug("接口返回的设备名称是：" + model?.equipment?.name)
            viewBinding.refresh.setColor()
            viewBinding.refresh.isRefreshing = false
            viewBinding.tvUserName.text = it.userinfo?.name
            viewBinding.tvUserId.text = it.userinfo?.username.toString()
            viewBinding.ivUserAvatar.loadHead(it.userinfo?.avatar)
            viewBinding.equip.root.setOnClickListener {
                BrowserActivity.start(
                    requireActivity(),
                    "deviceManagement_new?canshu=" + model?.equipment?.id.toString()
                )

            }
            it.todayArr?.apply {
                setTodayData(this)
            }
            setTryRide(it, it.tryride)
            setEquip(it.equipment)
            viewBinding.bikeMakeMoney.root.visibility = View.GONE
            viewBinding.bikeMakeMoney.root.visibility = View.VISIBLE
            if (System.currentTimeMillis() - lastUpdate >= 3000) {
                viewBinding.bikeMakeMoney.apply.isChecked = it.userinfo?.tryride == 1
                if (it.userinfo?.tryride == 1) {
                    viewBinding.bikeMakeMoney.root.visibility = View.GONE
                } else if (hasCar || ble || it.equipment != null) {
                    viewBinding.bikeMakeMoney.root.visibility = View.VISIBLE
                } else {
                    viewBinding.bikeMakeMoney.root.visibility = View.GONE
                }
            }
            viewBinding.bikeMakeMoney.apply.setOnClickListener {
                if (viewBinding.bikeMakeMoney.apply.isChecked) {
                    val show =
                        SpUtil.getString(requireActivity(), Constant.TRY_RIDE_LICENCE)
                    if (show != "1") {
                        TryRideLicenceShowDialog(
                            requireActivity() as MainActivity,
                            model?.agreement?.str ?: ""
                        ) {
                            if (it) {
                                update(viewBinding.bikeMakeMoney.apply.isChecked)
                            } else {
                                viewBinding.bikeMakeMoney.apply.isChecked = false
                            }
                        }.show()
                        return@setOnClickListener
                    }
                }
                update(viewBinding.bikeMakeMoney.apply.isChecked)
            }

        }
        viewBinding.refresh.setOnRefreshListener {
            loginViewModel.loadUserCenter()
        }
        viewBinding.tvTopBikeName.text = getString(R.string.un_connected)
        bleViewModel.bleConnStatus.observe(this) {
            when (it.connStatus) {
                STATUS_DEVICE_CONNECTED -> {
                    ble = true
                    showMessage(getString(R.string.bl_connected))
                    viewBinding.tvTopBikeName.text = model?.equipment?.name
                }

                STATUS_DEVICE_DISCONNECTED -> {
                    showMessage(getString(R.string.bl_disconnect))
                    ble = false
                    viewBinding.tvTopBikeName.text = getString(R.string.un_connected)
                }

                STATUS_DEVICE_SERVICE_READY -> {
                    showMessage(getString(R.string.bl_ready))
                    viewBinding.tvTopBikeName.text = getString(R.string.un_connected)
                }

                STATUS_DEVICE_CONNECTING -> {
                    showMessage(getString(R.string.bl_connecting))
                    viewBinding.tvTopBikeName.text = getString(R.string.un_connected)
                }

                5 -> {
                    ble = false
                    if (!failMsg) {
                        showMessage(getString(R.string.bl_connect_fail))
                        failMsg = true
                    }
                    viewBinding.tvTopBikeName.text = getString(R.string.un_connected)
                    lastMac = ""
                }
            }
        }
    }

    private fun checkHasCar() {
        requireActivity().intent?.getIntExtra("reg", -1)?.let {
            if (it == 1) {
                UpdateHasCarDialog(requireContext()) { _b ->
                    loginViewModel.updateHasCar(_b) {
                        hasCar = _b
                        setHasCarOrNoCar(hasCar, null)
                    }
                }.show()
            }
        }
    }

    private fun setHasCarOrNoCar(hasCar: Boolean, equip: Equip?) {
        if (hasCar || ble || equip != null) {
            viewBinding.todayData.root.visibility = View.VISIBLE
            viewBinding.rlRecommend.visibility = View.VISIBLE
            viewBinding.tryRideNum.text = model?.tryridenum.toString()
            viewBinding.noBike.root.visibility = View.GONE
        } else {
            viewBinding.todayData.root.visibility = View.VISIBLE
            viewBinding.rlRecommend.visibility = View.GONE
            viewBinding.noBike.root.visibility = View.VISIBLE
        }
        if (equip != null || ble) {
            viewBinding.equip.root.visibility = View.VISIBLE
        } else {
            viewBinding.equip.root.visibility = View.GONE
        }
    }

    private fun update(boolean: Boolean) {
        showLoading()
        loginViewModel.updateTryRide(viewBinding.bikeMakeMoney.apply.isChecked) {
            lastUpdate = System.currentTimeMillis()
            hideLoading()
        }
    }

    private var failMsg = false

    private fun setTodayData(todayArr: TodayArr) {
        viewBinding.todayData.option.text =
            getString(R.string.today_option, "3")
        viewBinding.todayData.progress.setProgress((todayArr.todaydistance / todayArr.todaytj.toFloat()).toFloat())
        viewBinding.todayData.todayTv.text = SpannableStringBuilder().let {
            val d = (todayArr.todaydistance.meterToKm()).toBigDecimal()
                .setScale(1, RoundingMode.HALF_DOWN)
                .toString()
            it.append(d + " ")
            it.setSpan(AbsoluteSizeSpan(18, true), 0, d.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            it.append("miles")
            it.append("\n")
            it.append(getString(R.string.today))
            it
        }
        if (todayArr.complete == 1) { //已完成
            viewBinding.todayData.todayTv.setTextColor(Color.parseColor("#08DCAA"));
            viewBinding.todayData.progress.setColor(Color.parseColor("#08DCAA"))
            viewBinding.todayData.todayDabiao.text =
                getString(R.string.done_mili, (todayArr.todaytj.meterToKm().toString()).toString())
            viewBinding.todayData.todayDabiao1.text = getString(R.string.done)
            viewBinding.todayData.todayDabiao1.setTextColor(Color.parseColor("#08DCAA"))
            viewBinding.todayData.icon.setBackgroundColor(Color.parseColor("#08DCAA"))
        } else if (todayArr.todaytj > todayArr.todaydistance) { //不够
            viewBinding.todayData.todayTv.setTextColor(Color.parseColor("#FA2C1E"));
            viewBinding.todayData.todayDabiao.text =
                getString(R.string.un_done)
            viewBinding.todayData.todayDabiao1.text =
                getString(R.string.milli_s, todayArr.todaydistance.meterToKm().toString())
            viewBinding.todayData.todayDabiao1.setTextColor(Color.parseColor("#FA2C1E"))
            viewBinding.todayData.icon.setBackgroundColor(Color.parseColor("#FA2C1E"))
        } else {
            //超过
            viewBinding.todayData.todayTv.setTextColor(Color.parseColor("#36BAFF"));
            viewBinding.todayData.todayDabiao.text =
                getString(
                    R.string.over_done,
                    (todayArr.todaydistance.meterToKm().toString()).toString()
                )
            viewBinding.todayData.todayDabiao1.text =
                getString(R.string.milli_s, todayArr.todaydistance.meterToKm().toString())
            viewBinding.todayData.icon.setBackgroundColor(Color.parseColor("#36BAFF"))
            viewBinding.todayData.todayDabiao1.setTextColor(Color.parseColor("#36BAFF"))
        }
    }

    override fun resumeAndNoHidden() {
        StatusBarHelper.showStatusBar(requireActivity(), false)
    }

    private fun setTryRide(userInfo: UserInfoResponseBean, tryRide: TryRide?) {
        viewBinding.one.visibility = View.GONE
        if (tryRide == null) {
            viewBinding.tryRide.root.visibility = View.GONE
        } else {
            viewBinding.tryRide.root.visibility = View.VISIBLE
            viewBinding.noBike.root.visibility = View.GONE
            viewBinding.tryRide.time.text = tryRide.createtime
            viewBinding.tryRide.nickname.text = tryRide.nickname
            viewBinding.tryRide.head.loadHead(tryRide.img)
            if (tryRide.applystatus == 1 && tryRide.tostatus == 1) {
                viewBinding.tryRide.phone.text = tryRide.mobile
            } else {
                viewBinding.tryRide.phone.text = "--"
            }
            viewBinding.tryRide.gender.text = tryRide.gender
            viewBinding.tryRide.addr.text = tryRide.address
            viewBinding.tryRide.country.text = tryRide.country
            //cstatus=0显示接受和取消按钮
            // cstatus=1和status=0显示等待接受
            //cstatus=1和status=1和isend=0显示取消按钮
            //status=1和cstatus=1和isend=1显示确认结束
            //status=1和cstatus=3和isend=1显示等待确认结束
            //status=3和cstatus=3和isend=1已结束 这个应该不需要展示出来
            when {
                tryRide.cstatus == 0 -> {
                    viewBinding.one.visibility = View.VISIBLE
                    viewBinding.tryRide.agree.visibility = View.VISIBLE
                    viewBinding.tryRide.refuse.visibility = View.VISIBLE
                    viewBinding.tryRide.twobutton.visibility = View.VISIBLE
                    viewBinding.tryRide.refuse.text = getString(R.string.refuse)
                    viewBinding.tryRide.agree.setOnClickListener {
                        showLoading()
                        loginViewModel.agreeTryRide(tryRide.id) {
                            if (it.isSuccessful) {
                                if (tryRide.issqr == 2) {
                                    viewBinding.tryRide.root.visibility = View.GONE
                                    showMessage(getString(R.string.handle_in_tuijina))
                                } else {
                                    showMessage(getString(R.string.success))
                                }
                            } else {
                                showMessage(it.msg)
                            }
                            hideLoading()
                        }
                    }
                    viewBinding.tryRide.refuse.setOnClickListener {
                        showLoading()
                        loginViewModel.refuseTryRide(tryRide.id) {
                            if (it.isSuccessful) {
                                showMessage(getString(R.string.success))
                            } else {
                                showMessage(it.msg)
                            }
                            hideLoading()
                        }
                    }
                }

                tryRide.cstatus == 1 && tryRide.status == 0 -> {
                    viewBinding.tryRide.refuse.text = getString(R.string.waiting_accept)
                    viewBinding.tryRide.agree.visibility = View.GONE
                    viewBinding.tryRide.refuse.setOnClickListener {

                    }
                }

                tryRide.status == 1 && tryRide.cstatus == 1 && tryRide.isend == 1 -> {
                    viewBinding.tryRide.refuse.text = getString(R.string.confirm_end)
                    viewBinding.tryRide.agree.visibility = View.GONE
                    viewBinding.tryRide.refuse.setOnClickListener {
                        showLoading()
                        loginViewModel.endTryRide(tryRide.id) {
                            hideLoading()
                            if (it.isSuccessful) {
                                AddCommentDialog(requireContext(),
                                    object : AddCommentDialog.CommentCallback {
                                        override fun callback(content: String) {
                                            showLoading()
                                            loginViewModel.commentTryRide(
                                                tryRide.id.toString(),
                                                content
                                            ) {
                                                hideLoading()
                                                if (it.isSuccessful) {
                                                    showMessage(getString(R.string.success))
                                                } else {
                                                    showMessage(it.msg)
                                                }
                                            }
                                        }

                                    }).show()
                            } else {
                                showMessage(it.msg)
                            }
                        }

                    }
                }

                tryRide.cstatus == 1 && tryRide.status == 1 && tryRide.isend == 0 -> {
                    viewBinding.tryRide.refuse.text = getString(R.string.cancel)
                    viewBinding.tryRide.agree.visibility = View.GONE
                    viewBinding.tryRide.refuse.setOnClickListener {
                        //取消 也走 拒绝
                        showLoading()
                        loginViewModel.refuseTryRide(tryRide.id) {
                            if (it.isSuccessful) {
                                showMessage(getString(R.string.success))
                            } else {
                                showMessage(it.msg)
                            }
                            hideLoading()
                            viewBinding.tryRide.root.visibility = View.GONE
                        }
                    }
                }

                tryRide.cstatus == 3 && tryRide.status == 1 && tryRide.isend == 1 -> {
                    viewBinding.tryRide.refuse.text = getString(R.string.waiting_confirm_end)
                    viewBinding.tryRide.agree.visibility = View.GONE
                    viewBinding.tryRide.refuse.setOnClickListener {
                    }
                }

                else -> {
                    viewBinding.tryRide.root.visibility = View.GONE
                }
            }
        }
        viewBinding.noBike.apply.setOnClickListener {
            val a = activity

            if (a is MainActivity) {
                val show = SpUtil.getString(requireActivity(), Constant.TRY_RIDE_LICENCE)
                if (show == "1") {
                    a.setCurrentTab(4)
                } else {
                    TryRideLicenceShowDialog(a, model?.agreement?.str ?: "") {
                        if (it) {
                            lifecycleScope.launch {
                                Request.getSuspend<Any>(
                                    "qixing/cycling/sendTryride",
                                    HashMap()
                                )
                            }
                            a.setCurrentTab(4)
                        }
                    }.show()
                }
            }
        }
    }

    private var lastMac = ""
    private fun setEquip(equip: Equip?) {
        if (equip == null) {
//            viewBinding.noEquip.root.visibility = View.VISIBLE
//            viewBinding.equip.root.visibility = View.GONE
//            viewBinding.noBike.root.visibility = View.VISIBLE
            viewBinding.tvTopBikeName.text = getString(R.string.un_connected)
//            viewBinding.noEquip.connect.setOnClickListener {
//                startActivity(Intent(requireActivity(), AddDeviceActivity::class.java))
//            }
        } else {
//            viewBinding.noBike.root.visibility = View.GONE
//            viewBinding.equip.root.visibility = View.VISIBLE
//            viewBinding.noEquip.root.visibility = View.GONE
            viewBinding.equip.tvTotalMileage.text = equip.totalmileage.toReadable()
            viewBinding.equip.tvRemainingMileage.text = equip.canmileage.toReadable()
            viewBinding.equip.tvLongestSingleRide.text = equip.danci.toReadable()
            viewBinding.equip.tvBikeName.text = equip.name
            viewBinding.llBikeName.visibility = View.VISIBLE
            val ele = equip.electricity?.toIntOrNull() ?: 0
            viewBinding.equip.elecProgress.progress = ele / 100.0
            viewBinding.equip.percent.text = "${ele}%"

            val mac = equip.sn_mac
            if (mac.isNullOrEmpty()) {
                //从服务器获取的mac地址是空，则停止连接蓝牙
                stopConnectNow()
                return
            }
            //服务器获取的mac和现在连接的mac地址不一样，则重新连接
            if (!Objects.equals(mac, lastMac)) {
                //先停止连接老的
                stopConnectNow()
                BleUtils.checkPermissionAndOpenBle(requireActivity()) {
                    if (it) {
                        lastMac = mac
                        EventBus.getDefault().post(EventBusBean(EventTag.EventTag_conn_ble, mac))
                    }
                }
            }
        }
    }

    private fun stopConnectNow() {
        if (!TextUtils.isEmpty(lastMac)) {
            EventBus.getDefault().post(EventBusBean(EventTag.EventTag_disconn_ble, lastMac))
        }
        lastMac = ""
    }

    private fun initData() {
        viewBinding.tvUserName.text = SpUtil.getString(requireActivity(), Constant.USER_NICK_NAME)
        viewBinding.tvUserId.text = SpUtil.getString(requireActivity(), Constant.USER_ID)
    }

    private fun setListener() {
        viewBinding.versionName.text = BuildConfig.VERSION_NAME
        viewBinding.ivEditInfo.setOnClickListener(this)
        viewBinding.llSetting.setOnClickListener {
            BrowserActivity.start(requireActivity(), "setings")
        }
        viewBinding.rlCyclingHistory.setOnClickListener {
            BrowserActivity.start(requireActivity(), "driveCalendar")
        }
        viewBinding.rlUseHelp.setOnClickListener {
            BrowserActivity.start(requireActivity(), "helpRobot")
        }
        viewBinding.llBikeName.setOnClickListener {
            BrowserActivity.start(requireActivity(), "chooseManagement")
        }
        viewBinding.rlHealthInsights.setOnClickListener {
            BrowserActivity.start(requireActivity(), "driveHealth")
        }
        viewBinding.llMedal.setOnClickListener {
            BrowserActivity.start(requireActivity(), "xunzhang")
        }
        viewBinding.rlRecommend.setOnClickListener {
            BrowserActivity.start(requireActivity(), "tuijian")
        }
        viewBinding.rlBounus.setOnClickListener {
            BrowserActivity.start(requireActivity(), "yongjin")
        }
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.rl_cycling_history -> startActivity(
                Intent(
                    requireActivity(),
                    AddDeviceActivity::class.java
                )
            )

            R.id.iv_edit_info -> BrowserActivity.start(requireActivity(), "userInfo")
            else -> {}
        }
    }
}